import { useMutation } from "react-relay";
import {useCallback, useState} from "react";
import { RecordSourceSelectorProxy, } from "relay-runtime";
import {useToast} from "customize-easy-ui-component";
const graphql = require("babel-plugin-relay/macro");

/*同步旧平台 设备台账
syncEqpFromLegacy(type:String!,offset:Int, limit:Int): Boolean!
* */
const mutation = graphql`
  mutation useSyncEqpMutation($type: String!,$arg: String,$pasw: String,$offset: Int) {
        syncEqpFromLegacy(type: $type, arg:$arg, pasw:$pasw, offset: $offset){
          id auid offs totl desc fireor{id username unit{id name}}
        }
  }
`;

export default function useSyncEqpMutation() {
  const [called, setCalled] =useState<boolean>(false);
  const [result, setResult] =useState<any>('');
  const [commit, doing] = useMutation(mutation);
  const toast = useToast();
  return {
    call:useCallback(
      (type: string, arg: string, pasw: string, offset?: number) => {
        let disposable= commit({
          variables: {
            type, arg, pasw, offset
          },
          onCompleted: (response) => {
            setResult((response as any).syncEqpFromLegacy);
            console.log("跑到syncEqpFromLegacy2输出=", response);
          },
          onError: error => {
            setResult( '报错');
            toast({
              title: "后端回答了",
              subtitle: '新Task的ID＝'+error,
              intent: "error"
            });
          }
        });
        //必须放在commit函数之后的，才会doing逻辑=true生效,doing+called逻辑,保障同步化
        setCalled(true);
        return disposable;
      },
      [commit, toast]
    ),
    doing,
    result,
    called,
    reset: ()=>{
      setCalled(false);
      //外部组件依赖于结果的轮动切换。 不可以直接保留旧的结果，必须清空它。
      //setResult(null);
    },
  };
}
